package com.javasm.adminapi.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import com.javasm.adminapi.module.system.dao.PermissionDao;
import com.javasm.adminapi.module.system.dto.MenuTypeDTO;
import com.javasm.adminapi.module.system.dto.PermissionQueryDTO;
import com.javasm.adminapi.module.system.entity.Permission;
import com.javasm.adminapi.module.system.entity.Role;
import com.javasm.adminapi.module.system.entity.RolePermission;
import com.javasm.adminapi.module.system.service.PermissionService;
import com.javasm.adminapi.module.system.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 权限表(Permission)表服务实现类
 *
 * @author makejava
 * @since 2025-10-14 21:47:37
 */
@Service("permissionService")
public class PermissionServiceImpl extends ServiceImpl<PermissionDao, Permission> implements PermissionService {

    @Resource
    PermissionDao permissionDao;
    @Autowired
    private ParameterNamesModule parameterNamesModule;

    @Override
    public List<Permission> getByRid(Long id) {
        //查询出当前角色对应的所有权限
        List<Permission> list = permissionDao.getByRid(id);
        List<Permission> orderly = orderly(list,id);
        //返回权限树形结构
        return orderly;
    }

    private List<Permission> orderly(List<Permission> list,Long id){
        //找出顶级权限
        List<Permission> collect = list.stream()
                .filter(permission -> permission.getParentId() != null && permission.getParentId() == -1)
                .collect(Collectors.toList());
        //循环填入次级权限
        collect.forEach(permission -> {
            List<Permission> collect1 = list.stream()
                    .map(c->{
                        if (permission.getId().equals(c.getParentId())){
                            if(id!=-1){
                                RolePermission rolePermission = rolePermissionService.getRolePermission(c.getId(),id);
                                c.setAdd(rolePermission.getAdd());
                                c.setUpdate(rolePermission.getUpdate());
                                c.setDelete(rolePermission.getDelete());
                            }
                            return c;
                        }
                        return null;
                    }).filter(Objects::nonNull).collect(Collectors.toList());
            permission.setChildList(collect1);
        });
        return collect;
    }

    @Override
    public List<Permission> getlist() {
        List<Permission> list = list();
        List<Permission> orderly = orderly(list,-1L);
        return orderly;
    }

    @Override
    public PageInfo<Permission> queryPage(PermissionQueryDTO permissionQueryDTO) {
        Integer pageNum = permissionQueryDTO.getPageNum()==null?1:permissionQueryDTO.getPageNum();
        Integer pageSize = permissionQueryDTO.getPageSize()==null?10:permissionQueryDTO.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getParentId,-1);
        List<Permission> list = list(queryWrapper);
        list.forEach(permission -> {
            queryWrapper.clear();
            queryWrapper.eq(Permission::getParentId,permission.getId());
            List<Permission> list1 = list(queryWrapper);
            //排序
            list1.sort(Comparator.comparingInt(Permission::getSort));
            permission.setChildList(list1);
        });
        PageInfo<Permission> permissionPageInfo = new PageInfo<>(list);
        return permissionPageInfo;
    }

    @Override
    @Transactional
    public void del(List<Long> collect) {
        //查询菜单
        List<Permission> list = listByIds(collect);
        //找出顶级菜单
        List<Long> collect1 = list.stream()
                .filter(permission -> permission.getParentId() == -1)
                .map(permission -> permission.getId())
                .collect(Collectors.toList());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Permission::getParentId,collect1);
        List<Permission> list1 = list(queryWrapper);
        list1.addAll( list);
        removeBatchByIds(list1);
        //将菜单关联的角色记录去掉
        List<Long> collect2 = list1.stream().map(a -> a.getId()).collect(Collectors.toList());
        rolePermissionService.deleteByPermissionIds(collect2);
    }

    @Resource
    RolePermissionService rolePermissionService;
    @Override
    @Transactional
    public void add(Permission permission) {
        //新增
        //首先校验，确定路径、名称不能重复
        LambdaQueryWrapper<Permission> eq = new LambdaQueryWrapper<Permission>()
                .eq(Permission::getPermissionUrl, permission.getPermissionUrl())
                .eq(Permission::getPermissionName, permission.getPermissionName());
        if (count(eq)>0){
            throw new JavasmException(ExceptionEnum.UrlOrName);
        }
        //校验通过后添加
        save(permission);
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(1L);
        rolePermission.setPermissionId(permission.getId());
        rolePermissionService.save(rolePermission);
    }

    @Override
    public void updatePermission(Permission permission) {
        //修改
        //首先校验，确定路径、名称不能重复，如果id相同可以重复
        LambdaQueryWrapper<Permission> eq = new LambdaQueryWrapper<Permission>()
                .eq(Permission::getPermissionUrl, permission.getPermissionUrl())
                .eq(Permission::getPermissionName, permission.getPermissionName());
        List<Permission> list = list(eq);
        list.forEach(permission1 -> {
            if(permission.getId().equals(permission1.getId())){
                throw new JavasmException(ExceptionEnum.UrlOrName);
            }
        });
        //校验通过后修改
        updateById(permission);
    }

    @Override
    public void updateStart(Permission permission) {
        Long id = permission.getId();
        Integer status = permission.getStatus();
        permissionDao.updateStatus(id,status);
    }

    @Override
    public List<MenuTypeDTO> getMenuType(Long id) {

        return permissionDao.getMenuType(id);
    }


}
